package uploadfile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import mybeans.Beans;



/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = null;
		Beans bean= new Beans();
		String say = "无描述";
		//收集数据的容器
		Map<String,Object> map = new HashMap<String, Object>();
		//创建磁盘工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//创建文件上传核心对象
		ServletFileUpload upload = new ServletFileUpload(factory);
		//解析request集合
		List<FileItem> parseRequest = null;
		try {
			System.out.println("进入");
			parseRequest = upload.parseRequest(request);
			if(parseRequest==null){
				System.out.println("为空");
			}
		} catch (FileUploadException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//遍历request集合
		for (FileItem fileItem : parseRequest) {
			//判断是普表单项还是文件表单项
			boolean formField = fileItem.isFormField();
			//是文件上传的表单项
				//获取上传的文件名字
				if(formField){
					String fieldName = fileItem.getFieldName();//获取表单项名字,也就是平时getParameter的那个name
					say = fileItem.getString("utf-8");//获取表单项的值,平时getParameter的那个name返回的值当然要编码
				}else{
					name = fileItem.getName();
					System.out.println("654156444444444"+name);
					//设置保存路径,也就是你根路径底下的一个文件夹中
					//String realPath = this.getServletContext().getRealPath("images");
					//获取输入流读取文件
					InputStream inputStream = fileItem.getInputStream();
					InputStream input= fileItem.getInputStream();
					//创建输出流写入文件,路径/图片名字
					OutputStream outputStream = new FileOutputStream("C:/Users/ASUS/workspace/PlantProject/WebContent/images"+"/"+name);
					OutputStream output = new FileOutputStream(this.getServletContext().getRealPath("images")+"/"+name);
					System.out.println(this.getServletContext().getRealPath("images")+"/"+name);
					//将文件写入到images中
					IOUtils.copy(inputStream, outputStream);
					IOUtils.copy(input, output);
					//关流
					inputStream.close();
					input.close();
					outputStream.close();
					output.close();
					fileItem.delete();
					//根据对象保存路径~(相对路径),一般数据库中的图片字段都是相对路径.总之添加数据时根据你数据库图片字段的格式添加
					map.put("path", "images/"+name);
				}
				
			
		}
		try {
			BeanUtils.populate(bean, map);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			//将表单没有提交到的数据封装到实体中,这个根据你设置的字段来封装
			Beans user = (Beans) request.getSession().getAttribute("user");
			String userID = user.getUserID();
			//调用service的添加商品方法
			int i = UploadService.addShare(userID, say, "images/"+name);
			if(i == 1){
				request.setAttribute("i", "1");
				System.out.println("上传成功");
			}
			
			
			
			//向所有的粉丝发去提醒
			new UploadService().sendTipsToFS(userID);
			
			
			//重定向跳转到列表显示页面
			response.sendRedirect(request.getContextPath()+"/MyShareServlet?page=1");
//					request.getRequestDispatcher("/MyShareServlet?page=1").forward(request, response);
		
	}

}
